#include "network_tools.h"

bool NetworkTools::isServerPortUse() {
    int server_fd = -1;
    server_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_address;
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(SERVER_PORT);
    server_address.sin_addr.s_addr = INADDR_ANY;
    int ret = bind(server_fd, (struct sockaddr *) &server_address, sizeof(server_address));

    close(server_fd);

    if (ret != -1) {
        return false;
    }

    return true;
}

string NetworkTools::encryptionMessage(string message) {
    message = MAGIC_HEAD + message;

    string public_key;
    string encryption_key = ENCRYPTION_KEY;

    for (int i = 0; i < encryption_key.length(); ++i) {
        if (i >= message.length()) {
            public_key += (char) ((int) encryption_key[i] ^ (int) '&');
        }
        public_key += (char) ((int) encryption_key[i] ^ (int) message[i]);
    }

    return public_key;
}

string NetworkTools::decryptionMessage(string public_key) {
    string magic_head = string(MAGIC_HEAD);
    string encryption_key = ENCRYPTION_KEY;

    string message;
    for (int i = 0; i < encryption_key.length(); ++i) {
        if (i >= public_key.length()) {
            message += (char) ((int) encryption_key[i] ^ (int) '&');
        }
        message += (char) ((int) encryption_key[i] ^ (int) public_key[i]);
    }

    int index = message.find('&');
    if (index != -1) {
        message = message.substr(0, index);
    }

    if (message.substr(0, magic_head.size()) != magic_head) {
        return "";
    }

    return message.substr(magic_head.size());
}
